package first.printABC; /**
 * @ClassName first.printABC
 * @description:
 * @author: 荣燊
 * @create: 2021-09-08 21:46
 **/

/**
 * 参考：https://blog.csdn.net/xiaokang123456kao/article/details/77331878?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link
 */
public class PrintABC1 {
    public static class ThreadPrint implements Runnable {
        private String name;
        private Object self;
        private Object prev;

        private ThreadPrint(String name, Object prev, Object self) {
            this.name = name;
            this.self = self;
            this.prev = prev;
        }

        @Override
        public void run() {
            int count = 10;
            while (count > 0) {
                synchronized (prev) {
                    synchronized (self) {
                        System.out.print(name);
                        count--;
                        self.notifyAll(); //唤醒其他线程竞争self锁，注意此时self锁并未立即释放
                    }
                    // 这是self锁才释放
                    try {
                        prev.wait(); //立即释放 prev锁，当前线程休眠，等待唤醒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();
        ThreadPrint threadPrint1 = new ThreadPrint("A", c, a);
        ThreadPrint threadPrint2 = new ThreadPrint("B", a, b);
        ThreadPrint threadPrint3 = new ThreadPrint("C", b, c);
        new Thread(threadPrint1).start();
        Thread.sleep(10);
        new Thread(threadPrint2).start();
        Thread.sleep(10);
        new Thread(threadPrint3).start();
        Thread.sleep(10);
    }
}
